import styled from 'styled-components';

interface IChildRef {
  count: number;
  addCount: () => void;
  subCount: () => void
}
function ChildComp(props: any,ref: any) {
  /* useImperativeHandle(ref, ()=>{
    return {
      // 暴露给父组件的方法或属性
    }
  }, [deps])
  ref: 父组件传递的ref对象
  createHandle: 返回值，返回一个对象，对象的属性就是子组件暴露给父组件的方法或属性
  deps?:[可选] 依赖项，当依赖项发生变化时，会重新调用createHandle函数，类似于useEffect的依赖项 */
  const [count, setCount] = useState(0);
  useImperativeHandle(ref,()=>{
    return {
      count,
      addCount: () => setCount(count + 1),
      subCount: () => setCount(count - 1)
    }
  });
  return (
    <div>
      <h3>我是子组件</h3>
      <div>count:{count}</div>
      <button onClick={() => setCount(count + 1)}>增加</button>
      <button onClick={() => setCount(count - 1)}>减少</button>
    </div>
  );
}
const Child = forwardRef<IChildRef>(ChildComp);
export default function useImperativeHandleComp() {
  const childRef = useRef<IChildRef>(null);
  const showRefInfo = () => {
    console.log(childRef.current);
  }
  return (
    <Wrapper>
      <div className="useImperativeHandleComp">
        <h2>我是父组件</h2>
        <button onClick={showRefInfo}>获取子组件信息</button>
        <button onClick={() => childRef.current?.addCount()}>操作子组件+1</button>
        <button onClick={() => childRef.current?.subCount()}>操作子组件-1</button>
        <br />
        <Child ref={childRef}/>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .useImperativeHandleComp {
    color: #000;
  }
`;
